from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL
from docx.opc.oxml import qn
from docx.shared import Pt  # 设置字号
from docx.shared import Cm  # 设置宽度，单位是cm
from docx.shared import RGBColor  # 设置字体颜色
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml import OxmlElement
from docx.oxml.ns import qn


def format_table(table):
    # # 表格内容居中&字体
    # for i in range(len(table.rows)):
    #     for j in range(len(table.columns)):
    #         table.cell(i, j).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    #         for par in table.cell(i, j).paragraphs:
    #             # horizontal centered
    #             par.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER  #
    #             for run in par.runs:
    #                 run.font.size = Pt(10)
    #                 run.font.name = 'Arial'
    #                 run.font.name = '宋体'
    #                 run.font.bold = True
    # 遍历表格中的每个单元格设置对齐方式 - 全部水平居中
    for row in table.rows:
        for cell in row.cells:
            cell.height = 1
            for paragraph in cell.paragraphs:
                paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                for run in paragraph.runs:
                    run.font.size = Pt(10.5)
                    # run.font.name = 'Arial'
                    run.font.name = u'黑体'
                    # run.font.bold = True # 加粗


def format_table2(table):
    # 遍历表格中的每个单元格设置对齐方式 - 全部水平居中
    for row in table.rows:
        for cell in row.cells:
            cell.height = 1
            for paragraph in cell.paragraphs:
                paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    table.alignment = WD_TABLE_ALIGNMENT.CENTER


class TableCount:
    def __init__(self, count):
        self.count = count

    def add_table_count(self):
        self.count = self.count + 1


def convert_str_to_float_3(value) -> str:
    if not value:
        return ''
    if isinstance(value, str):
        return "{:.3f}".format(float(value))
    elif isinstance(value, float):
        return "{:.3f}".format(value)
    return "{:.3f}".format(value)


def set_base_style(doc):
    style = doc.styles['Normal']
    # style.font.name = u'黑体'  # 必须先设置font.name
    style.font.name = 'Times New Roman'  # 必须先设置font.name
    style.font.size = Pt(10.5)
    style.element.rPr.rFonts.set(qn('w:eastAsia'), u'黑体')


def create_table(doc, row, col):
    table = doc.add_table(rows=row, cols=col, style="Light Shading")
    return table


def delete_table_first_row(table):
    # 把第一行横线去掉
    first_row = table.rows[0]
    for cell in first_row.cells:
        set_cell_border(cell, top={"sz": 0, "val": "single", "color": "#FFFFFF", "space": "0"})


def delete_table_first_last_row(table):
    # 把第一行和最后一行的横线去掉
    first_row = table.rows[0]
    last_row = table.rows[-1]
    for cell in first_row.cells:
        set_cell_border(cell, top={"sz": 0, "val": "single", "color": "#FFFFFF", "space": "0"})
    for cell2 in last_row.cells:
        set_cell_border(cell2, bottom={"sz": 0, "val": "single", "color": "#FFFFFF", "space": "0"})
    return


def set_cell_border(cell, **kwargs):
    """
    Set cell`s border
    Usage:
    set_cell_border(
    cell,
    top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
    bottom={"sz": 12, "color": "#00FF00", "val": "single"},
    left={"sz": 24, "val": "dashed", "shadow": "true"},
    right={"sz": 12, "val": "dashed"},
    )
    """
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    # check for tag existnace, if none found, then create one
    tcBorders = tcPr.first_child_found_in("w:tcBorders")
    if tcBorders is None:
        tcBorders = OxmlElement('w:tcBorders')
        tcPr.append(tcBorders)

    # list over all available tags
    for edge in ('left', 'top', 'right', 'bottom', 'insideH', 'insideV'):
        edge_data = kwargs.get(edge)
        if edge_data:
            tag = 'w:{}'.format(edge)
            # check for tag existnace, if none found, then create one
            element = tcBorders.find(qn(tag))
            if element is None:
                element = OxmlElement(tag)
                tcBorders.append(element)

            # looks like order of attributes is important
            for key in ["sz", "val", "color", "space", "shadow"]:
                if key in edge_data:
                    element.set(qn('w:{}'.format(key)), str(edge_data[key]))
